import jcore from '../jcore'
import ReqClass from './ReqClass'
import { configOptions } from './config'

// 封装wx的请求
export class WxRequest extends ReqClass {
    constructor(options) {
        super(options)
        // 快捷请求参数配置
        this.quickConfig = {
            apiGet: {
                method: 'get',
                header: {}
            },
            apiPost: {
                method: 'post',
                header: { 'content-type': 'application/x-www-form-urlencoded' }
            },
            apiJson: {
                method: 'post',
                header: { 'content-type': 'application/json;charset=UTF-8' }
            }
        }
    }
    // 请求入口
    mainApi(apiType, url, data) {
        let options = {}
        if (typeof url === 'object') {
            options = url
        } else if (arguments.length == 2) {
            options = { url }
        } else {
            options = { url, data }
        }
        return this.api(Object.assign(this.quickConfig[apiType], options))
    }
    // [重写]请求拦截器
    requestBefore(config) {
        let access_token = jcore.getLocal('access_token')
        if (access_token) {
            config.header.Authorization = access_token
        }
        return config
    }
    // [重写]响应拦截器
    responseBefore(response, options) {
        if (response.statusCode !== 200) {
            return this.toast('服务器正在维护...')
        }
        let res = response.data
        if (res.code === options.code.success) {
            return true
        } else if (res.code === options.code.logOut) {
            console.log('登录失效是否重新登录!')
            if (options.logOutNext === 1) {
                return jcore.tips('登录失效请重新登录!')
            }
            wx.clearStorageSync()
            jcore.showModal('登录失效是否重新登录!').then(res => {
                if (res) {
                    wx.navigateTo({ url: '/pages/login/login' });
                }
            })
        } else {
            let msg = res.message || '操作异常!'
            if (options.failLog) {
                this.toast(msg)
            } else {
                console.log(msg, '-->>> request fail')
            }
        }
        return false
    }
    // [重写]请求提示信息
    toast(msg) {
        jcore.tips(msg)
    }
}

// new WxRequest
const wxReq = new WxRequest(configOptions)

// [快捷请求]
// api get
export function apiGet(url, data) {
    return wxReq.mainApi('apiGet', url, data)
}
// api post form
export function apiPost(url, data) {
    return wxReq.mainApi('apiPost', url, data)
}
// api post json
export function apiJson(url, data) {
    return wxReq.mainApi('apiJson', url, data)
}